package login

import (
	"net/http"
	"strings"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"src/myaccount.go/src/model"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	session := sessions.Default(c)

	if strings.Trim(username, " ") == "" || strings.Trim(password, " ") == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Parameters can't be empty"})
		return
	}

	//数据库获取用户
	loginuser, err := model.GetUser(username)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"message": "用户名无效，或密码无效"})
		return
	}

	if loginuser.Password != model.Encrypt(password) {
		//c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentication failed"})
		c.JSON(http.StatusOK, gin.H{"message": "用户名密码不存在"})
		return
	}

	// Save the username in the session
	session.Set("userkey", username) // In real world usage you'd set this to the users ID
	if err := session.Save(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save session"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "Successfully authenticated user"})
}

func Logout(c *gin.Context) {
	session := sessions.Default(c)
	user := session.Get("userkey")
	if user == nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid session token"})
		return
	}
	session.Delete("userkey")
	if err := session.Save(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save session"})
		return
	}
	//c.JSON(http.StatusOK, gin.H{"message": "Successfully logged out"})
	c.HTML(http.StatusOK, "logout", gin.H{})
}

func AuthRequired(c *gin.Context) {
	session := sessions.Default(c)
	user := session.Get("userkey")
	if user == nil {
		// Abort the request with the appropriate error code
		//c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
		c.Redirect(http.StatusTemporaryRedirect, "/")
		return
	}
	// Continue down the chain to handler etc
	c.Next()
}

func Loginpage(c *gin.Context) {
	c.HTML(200, "login", gin.H{})
}

func Home(c *gin.Context) {
	c.HTML(http.StatusOK, "home", gin.H{})
}

func Me(c *gin.Context) {
	session := sessions.Default(c)
	user := session.Get("userkey")
	c.JSON(http.StatusOK, gin.H{"user": user})
}

func Status(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"status": "You are logged in"})
}
